package com.bjesc_b2c.app.appraiset.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.orhanobut.logger.Logger;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class BitmapUtil {

	//图片保存路径 sdCard的路径
//	private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getPath()+
//			File.separator+"bwf"+File.separator+"cache_img"+File.separator;

	/**
	 * 创建存图片的文件夹
	 */
//	private static void createCacheDir(){
//		File file = new File(CACHE_PATH);
//		if(!file.exists()){//当前文件夹不存在则创建
//			file.mkdirs();
//		}
//	}

	/**
	 * 保存一张图片
	 * @param bitmap
	 * @param imgUrl
	 */
	public static void saveBitmapToLocal(Bitmap bitmap,String imgUrl){
		Log.i("msg", "存图片："+imgUrl);
//		createCacheDir();
//		File img_file = new File(CACHE_PATH,getImg_FileName(imgUrl));
		File img_file = new File(imgUrl);
//		if(img_file.exists()){//如果图片存在则不报存
//			return;
//		}
		//保存图片
		OutputStream out = null;
		try {
			out =new FileOutputStream(img_file);
			bitmap.compress(CompressFormat.JPEG, 80, out);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
	/**
	 * 准备文件夹，文件夹若不存在，则创建
	 *
	 * @param filePath 文件路径
	 */
	public static void prepareFile(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
	/**
	 * 保存图片
	 * @param b
	 * @param file
	 */
	public static void saveBitmap(Bitmap b, File file) {
		String path = String.valueOf(file);
		try {
			FileOutputStream fout = new FileOutputStream(path);
			BufferedOutputStream bos = new BufferedOutputStream(fout);
			b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void saveImageToGallery(Context context, Bitmap bmp,String fileName) {
		// 首先保存图片
		File appDir = new File(Environment.getExternalStorageDirectory(), "pinggushi");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		final File file1Path = new File(file.getPath());
		Luban.with(context)
				.load(file1Path)                 //传人要压缩的图片//设定压缩档次，默认三挡
				.setCompressListener(new OnCompressListener() { //设置回调

					@Override
					public void onStart() {
						// TODO 压缩开始前调用，可以在方法内启动 loading UI
						Logger.d("压缩");
					}
					@Override
					public void onSuccess(File file) {
						Logger.d("压缩完成++"+file.getAbsolutePath());
						copyfile(file,file1Path,true);
						// TODO 压缩成功后调用，返回压缩后的图片文件

					}

					@Override
					public void onError(Throwable e) {
						// TODO 当压缩过去出现问题时调用
					}
				}).launch();    //启动压缩
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
		// 其次把文件插入到系统图库(这里会出现新的图片)
//		try {
//			MediaStore.Images.Media.insertImage(context.getContentResolver(),
//					file.getAbsolutePath(), fileName, null);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
		// 最后通知图库更新

	}


	public static void copyfile(File fromFile, File toFile,Boolean rewrite ){

		if(!fromFile.exists()){
			return;
		}

		if(!fromFile.isFile()){
			return;
		}
		if(!fromFile.canRead()){
			return;
		}
		if(!toFile.getParentFile().exists()){
			toFile.getParentFile().mkdirs();
		}
		if(toFile.exists() && rewrite){
			toFile.delete();
		}

		try {
			FileInputStream fosfrom = new FileInputStream(fromFile);
			FileOutputStream fosto = new FileOutputStream(toFile);

			byte[] bt = new byte[1024];
			int c;
			while((c=fosfrom.read(bt)) > 0){
				fosto.write(bt,0,c);
			}
			//关闭输入、输出流
			fosfrom.close();
			fosto.close();


		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(fromFile.exists() && rewrite){
			fromFile.delete();
		}
	}


	/**
	 * 获得图片
	 * @param imgUrl
	 * @return
	 */
	public static Bitmap getBitmapFromSDCard(String imgUrl){
		//图片的路径
//		String img_path =CACHE_PATH+getImg_FileName(imgUrl);
		return BitmapFactory.decodeFile(imgUrl);
	}
	/**
	 * 使用图片的网络地址 获取图片的文件名
	 */
//	private static String getImg_FileName(String imgUrl){
//		//先要加密去掉特殊字符
//		String fileName = MD5(imgUrl)+".jpeg";
//		return fileName;
//	}

	/**
	 * MD5加密
	 * @param msg
	 * @return
	 */
	private static String MD5(String msg){
		try {
			byte[] btinput = msg.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md_by = md.digest(btinput);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < md_by.length; i++) {
				int val = ((int)md_by[i])& 0xff;
				if( val < 16){
					sb.append("0");
				}else{
					sb.append(Integer.toHexString(val));
				}
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 	压缩  优化 图片
	 *  优化图片大小 和质量
	 * @param bitmap
	 * @param pixelW  要优化的宽度
	 * @param pixelH  要优化的高度
	 * @return
	 */
	public static Bitmap storeImage(Bitmap bitmap,float pixelW, float pixelH){
		//质量压缩
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 70, os);
		int options = 100;
		while ( os.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于160kb,大于继续压缩
			os.reset();//重置baos即清空baos
			bitmap.compress(Bitmap.CompressFormat.JPEG, options, os);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 15;//每次都减少10
		}
		//大小压缩
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;
		newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
		//比例压缩
		int w =bitmap.getWidth();
		int h = bitmap.getHeight();
		float hh = pixelH;
		float ww = pixelW;
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (w / ww);
		} else if (w < h && h > hh) {
			be = (int) (h / hh);
		}
		if (be <= 0){
			be = 1;
		}
		newOpts.inSampleSize = be;
		newOpts.inJustDecodeBounds = false;
		Bitmap bitmap1 = BitmapFactory.decodeStream(is, null, newOpts);
		return bitmap1;
	}

	public static Bitmap getimage(Bitmap bitmap) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		//现在主流手机比较多是1280*720分辨率，所以高和宽我们设置为
		float hh = 1280f;//这里设置高度为1280f
		float ww = 720f;//这里设置宽度为720f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (bitmap.getWidth() / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (bitmap.getHeight() / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
        newOpts.inJustDecodeBounds = false;
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}


	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 15;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	public static void zoomBitmap(Bitmap bmp, float size) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 85, out);
		float zoom = (float) Math.sqrt(size * 1024 / (float) out.toByteArray().length);
		Matrix matrix = new Matrix();
		matrix.setScale(zoom, zoom);
		Bitmap result = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
		out.reset();
		result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		while (out.toByteArray().length > size * 1024) {
			System.out.println(out.toByteArray().length);
			matrix.setScale(0.9f, 0.9f);
			result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
			out.reset();
			result.compress(Bitmap.CompressFormat.JPEG, 85, out);
		}
	}

}
